package com.selangshiwo.sina.httpclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.CookieOrigin;
import org.apache.http.cookie.CookieSpec;
import org.apache.http.cookie.CookieSpecFactory;
import org.apache.http.cookie.params.CookieSpecPNames;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.BrowserCompatSpec;
import org.apache.http.params.HttpParams;

import com.selangshiwo.Util;
import com.selangshiwo.sina.requst.RequestPack;
import com.selangshiwo.sina.result.IResultPack;
import com.selangshiwo.sina.result.ResultPack;
import com.selangshiwo.sina.result.ResultType;

public class SinaHttpClient extends DefaultHttpClient implements HttpClient , ISinaHttpClient{
	
	
	private static class SinaHttpClientInstance{
		static final SinaHttpClient HTTPCLIENT = new SinaHttpClient();
		static{
			//本方法只是把原有的校验策略重写成空方法，具体原因不明，有可能因为跨域的权限造成，有空研究。
			CookieStore cookieStore = new BasicCookieStore();
			SinaHttpClientInstance.HTTPCLIENT.setCookieStore(cookieStore);
			CookieSpecFactory csf = new CookieSpecFactory() {
					public CookieSpec newInstance(HttpParams arg0) {
						return new BrowserCompatSpec(){
							@Override
							public void validate(Cookie cookie, CookieOrigin origin){
								//校验方法
							}
						};
						
					}
			};
			SinaHttpClientInstance.HTTPCLIENT.getCookieSpecs().register("weibo", csf);
			SinaHttpClientInstance.HTTPCLIENT.getParams().setParameter(ClientPNames.COOKIE_POLICY, "weibo") ;
			SinaHttpClientInstance.HTTPCLIENT.getParams().setParameter(CookieSpecPNames.SINGLE_COOKIE_HEADER, true);
		}
	}
	
	public static SinaHttpClient getInstance(){
		//HttpClientParams.setCookiePolicy(SinaHttpClientInstance.HTTPCLIENT.getParams(), CookiePolicy.BROWSER_COMPATIBILITY );
		return SinaHttpClientInstance.HTTPCLIENT ;
	}
	
	//彻底封装,传入Url带参数
	
	public IResultPack getRequest(RequestPack request , Class<?> pack){
		return getRequest(request , pack , null);
	}
	
	public IResultPack postRequest(RequestPack request  ,Class<?> pack ){
		return postRequest( request  , pack , null );
	}
	
	@Override
	public IResultPack getRequest(RequestPack request , Class<?> pack , ResultType type) {
		IResultPack result = null ;
		try {
			result = (IResultPack) pack.newInstance() ;	//why
			HttpGet get = (HttpGet) request.getHttpMethod();
			String strResponse = readHtml(this.execute(get));
			get.abort() ;
			result.init( strResponse,  type );
			
		} catch (ClientProtocolException e) {
			Util.err("客户端协议异常!");
			e.printStackTrace();
		} catch (IOException e) {
			Util.err("请求异常！");
			e.printStackTrace();
		} catch (Exception e) {
			Util.err("数据解析异常");
			e.printStackTrace();
		}
		return result;
	}
	
	@Override
	public IResultPack postRequest(RequestPack request  ,
			Class<?> pack , ResultType type){

		ResultPack result = null ;
		
		try {
			result = (ResultPack)pack.newInstance() ;
			
			HttpPost httpPost = (HttpPost) request.getHttpMethod();
			
			httpPost = setHeads(httpPost);
			
			String strResponse = readHtml(this.execute(httpPost));
			
			httpPost.abort() ;
			
			result.init(strResponse, type) ;
			
		} catch (Exception e) {
			Util.err("数据解析异常");
			e.printStackTrace();
		}finally{
			//this.getConnectionManager().shutdown();
		}
		
		return result ;
	}
	
	@SuppressWarnings("deprecation")
	private String readHtml(HttpResponse response) throws UnsupportedEncodingException, IllegalStateException, IOException{
		StringBuffer sb = new StringBuffer("");	
		HttpEntity entity = response.getEntity() ;
		BufferedReader br = new BufferedReader(new InputStreamReader(
				entity.getContent(), "GBK"));

		String line = null ;
		while((line = br.readLine()) != null){
			sb.append(line.replaceAll("\r", "").replaceAll("\n", ""));
		}
		
		entity.consumeContent() ;
		
		String strResponse = sb.toString() ;
		
		return strResponse ;
	}
	
	private HttpPost setHeads(HttpPost httpPost){
		//公共头
		//稍后改到公共参数
		httpPost.setHeader("User-Agent",
		"Mozilla/5.0 (X11; Linux i686; rv:5.0) Gecko/20100101 Firefox/5.0");
		httpPost.setHeader("Referer", "http://weibo.com/");
		httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

		return httpPost ;
	}

}
